<template>
  <t-space direction="vertical">
    <!-- 按钮操作区域 -->
    <template>
      <t-space direction="vertical" style="width: 100%">
        <t-row justify="space-between">
          <t-space>
            <div class="box">
              <t-space :size="8">
                <t-button variant="outline" theme="primary" :disabled="selectedRowKeys.length === 0" @click="remind"
                  >发送提醒</t-button
                >
                <t-button variant="outline" theme="danger" :disabled="selectedRowKeys.length === 0" @click="assigns"
                  >批量指派</t-button
                >
              </t-space>
            </div>
          </t-space>
          <t-space>
            <t-radio-group default-value="1" @change="changeRadio">
              <t-radio-button value="1">全部</t-radio-button>
              <t-radio-button value="2">与我相关</t-radio-button>
            </t-radio-group>
            <t-input autofocus style="width: 200px" @change="search" clearable placeholder="请输入">
              <search-icon slot="prefix-icon"></search-icon>
            </t-input>
          </t-space>
        </t-row>
      </t-space>
    </template>

    <t-table
      rowKey="id"
      :data="data"
      :columns="columns"
      :sort="sort"
      @sort-change="sortChange"
      :showSortColumnBgColor="true"
      :filter-value="filterValue"
      @filter-change="onFilterChange"
      :hover="hover"
      :size="size"
      :table-layout="tableLayout ? 'auto' : 'fixed'"
      :filterRow="() => null"
      cellEmptyContent="-"
      :selected-row-keys="selectedRowKeys"
      @select-change="rehandleSelectChange"
    >
      <template #reviewName="{ row }">
        <div v-if="row.reviewName" style="display: flex; align-items: center">
          <user-icon />
          <span style="margin-left: 3px">{{ row.reviewName }}</span>
        </div>
        <div v-else>-</div>
      </template>
      <template #disposalName="{ row }">
        <div v-if="row.disposalName" style="display: flex; align-items: center">
          <user-icon />
          <span style="margin-left: 3px">{{ row.disposalName }}</span>
        </div>
        <div v-else>-</div>
      </template>
      <template #reviewStopTime="{ row }">
        <span v-if="!row.reviewStopTime">-</span>
        <div
          v-if="row.reviewStopTime"
          style="display: flex; align-items: center"
          :style="{ color: new Date(row.reviewStopTime) < Date.now() - 8.64e7 ? 'var(--td-error-color)' : '#000' }"
        >
          <time-icon />
          <span style="margin-left: 3px">
            {{ row.reviewStopTime.slice(0, 11) }}
          </span>
        </div>
      </template>
    </t-table>
    <t-pagination
      v-model="pagination.defaultCurrent"
      @change="pageChange"
      :total="pagination.total"
      :page-size.sync="pagination.defaultPageSize"
      show-jumper
    />
    <t-dialog
      :visible="bodyVisible"
      header="批量指派风险"
      :onClose="bodyClose"
      :onConfirm="bodyClose"
      :closeOnOverlayClick="false"
      width="720px"
    >
      <div slot="body">
        <t-form layout="inline" :data="formData" labelWidth="calc(5em + 24px)" ref="form" scrollToFirstError="smooth">
          <t-form-item label="风险负责人" requiredMark>
            <t-select v-model="formData.principalValue" :options="riskSelection" placeholder="请选择风险负责人">
              <user-icon slot="prefixIcon" />
            </t-select>
          </t-form-item>
          <t-form-item label="截止时间" requiredMark>
            <t-date-picker
              v-model="formData.principalDeadline"
              clearable
              :disableDate="disableDate"
              format="YYYY-MM-DD  hh:mm:ss"
              placeholder="请选择处置截至日期"
            />
          </t-form-item>
          <t-form-item label="风险审核人" requiredMark>
            <t-select v-model="formData.verifierValue" :options="riskSelection" placeholder="请选择风险处置人">
              <user-icon slot="prefixIcon" />
            </t-select>
          </t-form-item>
          <t-form-item label="截止时间" requiredMark>
            <t-date-picker
              :disableDate="disableDate"
              v-model="formData.verifierDeadline"
              clearable
              format="YYYY-MM-DD  hh:mm:ss"
              placeholder="请选择审核截至日期"
            />
          </t-form-item>
          <t-form-item label="处置方案">
            <div>
              <t-textarea
                v-model="formData.disposalScheme"
                style="width: 303%"
                class="textarea"
                placeholder="批量风险指派适合可以合并一同处置的多条风险，且共用相同的处置方案。一般情况下，建议单独指派，设定更具针对性的处置方案。"
                :autosize="{ minRows: 3, maxRows: 20 }"
              />
            </div>
          </t-form-item>
        </t-form>
      </div>
      <template #footer>
        <t-space class="t-btn">
          <t-button @click="bodyClose">取消</t-button>
          <t-button @click="sub">提交</t-button>
        </t-space>
      </template>
    </t-dialog>
  </t-space>
</template>
<script lang="jsx">
import { SearchIcon, DeleteIcon, EditIcon, EllipsisIcon, UserIcon, TimeIcon } from 'tdesign-icons-vue';
import { DialogPlugin } from 'tdesign-vue';
import { mapState } from 'vuex';
import { tagOptions } from '@/constants/risk-assessment-governance';

import { deleteRiskList, sendRemind, sendrsAssign } from '@/service/risk-assessment/governance/index';
import { requestUserByOrg } from '@/service/business-management/role';
import { debounce } from '@/utils';

export default {
  components: {
    SearchIcon,
    UserIcon,
    TimeIcon,
  },
  data() {
    return {
      // 批量指派对话框
      bodyVisible: false,
      total: 0,
      data: [],
      filterValue: {
        createTime: [],
      },
      // 选中行
      selectedRowKeys: [],
      // 操作的关键词 筛选，排序
      oprationkW: {},
      size: 'medium',
      tableLayout: false,
      hover: true,
      showHeader: true,
      // 排序
      sort: {
        // 按照 status 字段进行排序
        sortBy: 'id',
        // 是否按照降序进行排序
        descending: false,
      },
      columns: [
        {
          colKey: 'row-select',
          type: 'multiple',
        },
        {
          // 序号列，设置 colKey = serial-number 即可
          colKey: 'id',
          title: 'ID',
          ellipsis: true,
          // width: '110',
          // 对齐方式
          align: 'start',
          // 设置列类名
          className: 'custom-column-class-name',
          // 设置列属性
          attrs: {
            'data-id': 'first-column',
            style: {},
          },
        },
        {
          // width: 300,
          colKey: 'description',
          title: '风险描述',
          // align: 'start',
          // ellipsis: true,
          cell: (h, { row }) => <span style="color: #0052D9;">{row.description}</span>,
        },
        {
          colKey: 'state',
          // width: 200,
          title: '状态',
          sorter: true,
          // 输入框过滤配置
          cell: (h, { row }) => (
            <t-tag variant="light-outline" theme={tagOptions[row.status].theme}>
              {row.state}
            </t-tag>
          ),
          // 多选过滤配置
          filter: {
            type: 'multiple',
            resetValue: [],
            // 是否显示重置取消按钮，一般情况不需要显示
            showConfirmAndReset: true,
            list: [
              { label: '待指派', value: '1' },
              { label: '待处置', value: '2' },
              { label: '待审核', value: '3' },
              { label: '已完成', value: '4' },
            ],
          },
        },
        {
          colKey: 'disposalName',
          title: '处置人',
          sortType: 'all',
          sorter: true,
          ellipsis: true,
          ellipsisTitle: false,
          // 多选过滤配置
          filter: {
            type: 'multiple',
            resetValue: [],
            // 是否显示重置取消按钮，一般情况不需要显示
            showConfirmAndReset: true,
            list: [],
          },
        },
        {
          colKey: 'reviewName',
          title: '审核人',
          sortType: 'all',
          sorter: true,
          ellipsis: true,
          ellipsisTitle: false,
          // 多选过滤配置
          filter: {
            type: 'multiple',
            resetValue: [],
            // 是否显示重置取消按钮，一般情况不需要显示
            showConfirmAndReset: true,
            // { label: 'All', checkAll: true },
            list: [],
          },
        },
        {
          colKey: 'reviewStopTime',
          title: '截至日期',
          // width: 200,
          ellipsis: true,
          ellipsisTitle: false,
          sortType: 'all',
          sorter: true,
        },
        {
          colKey: 'action',
          title: '操作',
          width: 200,
          // 增、删、改、查 等操作
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          cell: (h, { row }) => (
            <div class="tdesign-table-demo__table-operations">
              <t-button variant="text" onClick={() => this.edit(row)}>
                <EditIcon></EditIcon>
              </t-button>
              <t-button variant="text" onClick={() => this.delete(row)}>
                <DeleteIcon></DeleteIcon>
              </t-button>
              <t-button variant="text" onClick={() => this.ellipsis(row)}>
                <EllipsisIcon></EllipsisIcon>
              </t-button>
            </div>
          ),
        },
      ],
      // 分页器
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        total: 0,
      },
      // 对话框表单数据
      formData: {
        principalValue: '', // 风险处置人
        verifierValue: '', // 风险审核人
        principalDeadline: '',
        verifierDeadline: '',
        disposalScheme: '',
      },
      riskSelection: [],
    };
  },
  computed: {
    ...mapState('riskGovernance', ['riskList']),
    ...mapState('user', ['userInfo']),
  },
  mounted() {
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      const pageSize = this.pagination.defaultPageSize;
      const pageNum = this.pagination.defaultCurrent;
      const roleDTO = { ...this.oprationkW, pageNum, pageSize };
      await this.$store.dispatch('riskGovernance/requireRiskList', roleDTO);
      // this.selectedRowKeys=[]

      this.data = this.riskList.data?.resultRsVO.list;
      this.pagination.total = this.riskList.data?.resultRsVO.total;

      // 渲染筛选框选项内容
      const disposalNameSet = this.riskList.data.disposalNameSet.map((item) => item.rsUserName || 'null');
      this.columns[4].filter.list = disposalNameSet;
      const reviewNameSet = this.riskList.data.reviewNameSet.map((item) => item.rsUserName || 'null');
      this.columns[5].filter.list = reviewNameSet;
    },
    // 输入框搜索
    search: debounce(function fn(value) {
      this.oprationkW.inputContent = value;
      // 如果没有搜索参数value，接口要求也不传key
      if (!value) this.$delete(this.oprationkW, 'value');
      this.getUserInfo();
    }, 1000),
    // 排序
    sortChange(sort) {
      this.sort = sort;
      this.sortRequest(sort);
    },
    sortRequest(sort) {
      // 不排序的时候 不传参数
      if (!sort) {
        this.$delete(this.oprationkW, 'orderColum');
        this.$delete(this.oprationkW, 'orderType');
        this.getUserInfo();
        return;
      }
      let orderColum;
      let orderType;
      orderType = 'desc';
      if (sort?.descending) orderType = 'asc';

      orderColum = sort?.sortBy;
      if (sort?.sortBy === 'state') orderColum = 'status';
      // 如果过滤也同时存在
      if (this.oprationkW.roleNameList) {
        this.oprationkW = { ...this.oprationkW, orderColum, orderType };
        this.sortRequest();
        return;
      }

      // 只有排序的时候
      this.oprationkW = { ...this.oprationkW, orderColum, orderType };
      this.getUserInfo();
    },
    // 过滤
    onFilterChange(filters) {
      this.filterValue = {
        ...filters,
        createTime: filters.createTime || [],
      };
      this.filterRequest(this.filterValue);
    },
    filterRequest(filters) {
      // 审核人过滤条件
      const reviewNameList = [];
      const disposalNameList = [];
      // eslint-disable-next-line array-callback-return
      filters.disposalName?.map((item) => {
        this.riskList.data.disposalNameSet.forEach((val) => {
          if (item === val.rsUserName) disposalNameList.push(val.rsUserId);
        });
      });

      filters.reviewName?.forEach((item) => {
        this.riskList.data.reviewNameSet.forEach((val) => {
          if (item === val.rsUserName) reviewNameList.push(val.rsUserId);
        });
      });
      const statusList = filters.state;
      this.oprationkW = { ...this.oprationkW, disposalNameList, reviewNameList, statusList };

      // 如果没有过滤参数value，接口要求也不传key
      if (!disposalNameList || disposalNameList?.length === 0) this.$delete(this.oprationkW, 'disposalNameList');
      if (!reviewNameList || reviewNameList?.length === 0) this.$delete(this.oprationkW, 'reviewNameList');
      if (!statusList || statusList?.length === 0) this.$delete(this.oprationkW, 'statusList');
      this.pagination.defaultCurrent = 1;
      this.getUserInfo();
    },
    pageChange({ current, pageSize }) {
      this.pagination.defaultCurrent = current;
      this.pagination.defaultPageSize = pageSize;
      this.getUserInfo();
    },
    ellipsis() {
      this.$message.info('该功能未开发，敬请期待');
    },
    async delete(row) {
      const dialog = DialogPlugin.confirm({
        theme: 'warning',
        header: '警告',
        body: '再次确认是否删除？',
        onConfirm: () => {
          deleteRiskList(row.id).then((res) => {
            if (!res || res.isError) return;
            this.$message.success('删除成功');
            this.getUserInfo({ ...this.oprationkW });
            this.$bus.$emit('updateDashboard');
            dialog.destroy();
          });
        },
      });
    },
    edit(row) {
      const { id } = row;
      this.$router.push({
        path: '/risk-assessment/governance/procedure',
        query: { id },
      });
      // this.$router.push(`/risk-assessment/governance/procedure?id=${rowData.id}`)
    },
    // 选中行 todo
    rehandleSelectChange(value) {
      this.selectedRowKeys = value;
    },
    // 单选框切换
    changeRadio(val) {
      this.pagination.defaultCurrent = 1;
      if (val === '2') this.oprationkW = { ...this.oprationkW, myselfId: this.userInfo.id };
      else this.$delete(this.oprationkW, 'myselfId');
      this.getUserInfo();
    },
    // 发送提醒
    async remind() {
      const ids = this.selectedRowKeys;
      let remindMark = false;
      for (let i = 0; i < this.data.length; i++) {
        if (ids.includes(this.data[i].id)) {
          if (!this.data[i].reviewName && !this.data[i].disposalNameId) {
            remindMark = true;
            break;
          }
        }
      }
      if (remindMark) {
        this.$message.error('处置人与审核人必须存在一位');
        return;
      }
      const res = await sendRemind(ids);
      if (res?.code === 200) {
        this.$message.success(res.message);
        this.selectedRowKeys = [];
      }
    },
    // 发送指派
    async assigns() {
      // 请求选择框选项的内容
      const riskOwners = await requestUserByOrg();
      const flag = this.data.some((item) => {
        if (this.selectedRowKeys.includes(item.id)) {
          return item.status !== 1;
        }
        return false;
      });
      if (flag) {
        this.$message.warning('待指派状态下才能进行指派');
        return;
      }

      this.bodyVisible = true;
      this.$bus.$emit('updateDashboard');
      this.riskSelection = riskOwners.map((item) => ({
        label: item.name,
        value: item.id,
      }));
    },
    // 关闭对话框
    bodyClose() {
      this.bodyVisible = false;
      this.formData.principalValue = '';
      this.formData.principalDeadline = '';
      this.formData.verifierValue = '';
      this.formData.verifierDeadline = '';
      this.formData.disposalScheme = '';
    },
    // 进行指派
    async sub() {
      const { principalValue, verifierValue, principalDeadline, verifierDeadline } = this.formData;
      if (!principalValue || !verifierValue || !principalDeadline || !verifierDeadline) {
        this.$message.warning('填写');
        return;
      }
      const rsAssignDTOs = {
        disposalNameById: this.formData.principalValue,
        disposalStopTime: this.formData.principalDeadline,
        reviewNameById: this.formData.verifierValue,
        reviewStopTime: this.formData.verifierDeadline,
        ids: this.selectedRowKeys,
        disposalScheme: this.formData.disposalScheme,
      };
      const res = await sendrsAssign(rsAssignDTOs);
      if (res.code === 200) {
        this.$message.success(res.message);
        this.bodyVisible = false;
        this.getUserInfo();
        this.selectedRowKeys = [];
        this.formData.principalValue = '';
        this.formData.principalDeadline = '';
        this.formData.verifierValue = '';
        this.formData.verifierDeadline = '';
        this.formData.disposalScheme = '';
      }
    },
    disableDate(time) {
      return time.getTime() < Date.now() - 8.64e7; // 只能选择今天以及今天之后的日期，如果没有后面的-8.64e7就是不可以选择今天的
      // return time.getTime() > Date.now() - 8.64e6; // 选择今天以及今天之前的日期，如果没有后面的-8.64e6就是不可以选择今天的
    },
  },
};
</script>
<style lang="less" scoped>
.t-btn {
  display: flex;
  justify-content: center;
}
.textarea {
  width: 1000px;
}
.t-textarea__inner {
  height: 400px;
}
</style>
